import store from '../store'
import {getToken,getUser} from "@/utils/auth";

export const apiUrl = '' 
export const baseUrl = process.env.VUE_APP_BASEURL 
export const goBack = () => {
  // @ts-ignore
  document.querySelector('body')
    .classList
    .remove('el-popup-parent--hidden')
  location.href = history.state.back ? `#${history.state.back}` : ''
  location.reload()
}

export const isMobile = (RATIO=3, WIDTH=1024) => {
  //const rect = document.body.getBoundingClientRect()
  //return (rect.width - RATIO) < WIDTH
  return false
}

export const resizeHandler = () => {
  if (!document.hidden) {
    const mobile = isMobile()
    store.dispatch('ToggleDevice', mobile ? 'mobile' : 'desktop')
    store.dispatch(mobile ? 'CloseSideBar' : 'OpenSideBar', {withoutAnimation: true})
  }
}

let heartTimer: any = -1

const sendHeart = (ws) => {
  if (heartTimer) { clearTimeout(heartTimer) }
  heartTimer = setTimeout(function heart() {
    const data = JSON.stringify({ type: 6, data: getToken() })
    ws.send(data)
    heartTimer = setTimeout(heart, 5 * 1000)
  }, 5 * 1000)
}

export const createWebsocket = (callback, closed: any = null) => {
  try {
    const origin = location.origin.replace('http', 'ws')  
    const user = getUser() 
    const url = `${origin}/sales/websocket/${user.id}` 
    const ws = new WebSocket(url)
    ws.onopen = (() => sendHeart(ws))
    ws.onmessage = ((res) => callback(res))
    ws.onclose = ((e) => {
      clearTimeout(heartTimer)
      console.log(`websocket closed`)
      if (closed) closed()
    })
    ws.onerror = ((e) => {
      clearTimeout(heartTimer)
      console.log(`websocket error`)
    })
    return ws
  } catch (e) {
    console.log(e)
  }
}

export const isMobileDevice = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

export const liveStreamTypes = {
  0: '原画',
  1: '识别',
  2: '内部',
  3: '外部',
}
